import React, {useState, useEffect} from 'react'

import {Container, LikeContainer, CollectContainer} from './style'

import {Space, Divider, Anchor, message, Spin, Badge } from 'antd'

import { LikeOutlined, StarOutlined, StarTwoTone, LikeTwoTone, LikeFilled, StarFilled } from '@ant-design/icons'

import {connect} from 'react-redux'
import {changeDetailTopDis, changeDetailObj} from '../../../store/actionCreators'

import MyCard from '../../../components/MyCard'

import countFormat from '../../../assets/js/countFormat'

import moment from 'moment'
import 'moment/locale/zh-cn'

import {PhotoSlider} from 'react-photo-view'
import 'react-photo-view/dist/index.css'

import ArticleRequest from '../../../request/article_request'

const article_request = new ArticleRequest()

const { Link } = Anchor


function Detail(props){
    const {match, history, changeDetailTopDis, changeDetailObj} = props

    const [articleObj, setArticleObj] = useState({
        lastArticle: {},
        nextArticle: {},
        contents: []
    })

    const [imagePreviewShow, setImagePreviewShow] = useState(false)
    const [imagePreviewIndex, setImagePreviewIndex] = useState(false)
    const [imageList, setImageList] = useState([])

    const sumMap = new Map() // 统计目录中重复条目的个数

    const getArticleById = (isFirst) => {
        article_request.getArticleById({
            id: match.params.id
        }).then(res => {
            setArticleObj({
                ...res,
                contents: JSON.parse(res.contents || '[]').map(item => {
                    if(Array.isArray(item)){
                        return item.map(item => {
                            return {
                                title: item,
                                link: deleteSpecialCode(item)
                            }
                        })
                    }else{
                        return {
                            title: item,
                            link: deleteSpecialCode(item)
                        }
                    }
                })
            })
            previewArticle(res.contentMd || '', isFirst)
            if(isFirst){
                changeDetailObj(res)
            }
        })
    }

    /* eslint-disable */
    // 使用Vidtor官方api显示文章内容
    const previewArticle = (content, isFirst) => {
        Vditor.preview(document.getElementById('article-content'), content, {
            after: () => {
                if(isFirst){
                    makeImagePreview()
                    listenATagClick()
                }
            }
        })
    }
    /* eslint-disable */

    const collectArticle = (id, title, desc) => {
        article_request.collectArticle({
            id,
            title,
            desc
        }).then(res => {
            message.success('已加入收藏')
            getArticleById()
        })
    }

    const likeArticle = (id) => {
        article_request.likeArticle({
            id
        }).then(res => {
            getArticleById()
        })
    }

    const deleteSpecialCode = (text) => { //特殊字符包括空格全部替换成 -
        let result = text.replace(/[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g, '-')
        let val = sumMap.get(result)
        if(val){
            sumMap.set(result, val + 1)
            for (let index = 0; index < val; index++) {
                result = result + '-'
            }
        }else{
            sumMap.set(result, 1)
        }
        return result
    }

    const addReadCount = () => {
        article_request.addReadCount({
            id: match.params.id
        })
    }

    // 该页所有图片加上预览
    const makeImagePreview = () => {
        let list = [];
        [...document.getElementById('article-content').getElementsByTagName('img')].forEach((item, index) => {
            list.push(item.src)
            item.onclick = () => {
                setImagePreviewShow(true)
                setImagePreviewIndex(index)
            }
        })
        setImageList(list)
    }

    // 监听文章中a 标签的点击事件
    const listenATagClick = () => {
        [...document.getElementById('article-content').getElementsByTagName('a')].forEach((item, index) => {
            item.onclick = (e) => {
                e.preventDefault()
                window.open(item.href)
            }
        })
    }

    // 监听详情页滚动事件，记住滚动位置
    const getScrollPosition = () => {
        document.getElementById('article-top-c').onscroll = (e) => {
            if(history.location.pathname.indexOf('/article/detail') !== -1){
                changeDetailTopDis(e.target.scrollTop)
            }
        }
    }

    useEffect(() => {
        getArticleById(true)
        addReadCount()
        document.getElementById('article-top-c').scrollTop = 0
    }, [match.params.id])
    useEffect(() => {
        getScrollPosition()
        return () => {
            changeDetailTopDis(0)
        }
    }, [])
    return (
        <Container>
            <PhotoSlider
                images={imageList.map(item => ({ src: item }))}
                visible={imagePreviewShow}
                onClose={() => setImagePreviewShow(false)}
                index={imagePreviewIndex}
                onIndexChange={setImagePreviewIndex}
            />
            <div className="article-c">
                <MyCard notTitle={true}>
                    <div className="article">
                        <div className="title">{articleObj.title}</div>
                        <div className="desc">
                            <span>上一次更新：{articleObj.updateDate ? moment(Number(articleObj.updateDate)).fromNow() : ''}</span>
                            <span>{countFormat(articleObj.readcount || 0)} 阅读</span>
                        </div>
                        <Spin spinning={!articleObj.contentMd}>
                        <div className="content vditor-reset" id="article-content"></div>
                        </Spin>
                        <div className="footer">
                            <div className="operate">
                                <Space key="list-vertical-like-o" style={{cursor: 'pointer'}} onClick={() => likeArticle(articleObj.id)}>
                                    {articleObj.isLike ? <LikeTwoTone twoToneColor="#eb2f96"/> : <LikeOutlined/>}
                                    {countFormat(articleObj.likecount || 0)}
                                </Space>
                                <Divider type="vertical" style={{margin: '0 20px'}}/>
                                <Space key="list-vertical-star-o" style={{cursor: 'pointer'}} onClick={() => collectArticle(articleObj.id, articleObj.title, articleObj.desc)}>
                                    {articleObj.isCollect ? <StarTwoTone twoToneColor="#ffd139"/> : <StarOutlined/>}
                                </Space>
                            </div>
                            <div className="page-change">
                                <p onClick={() => articleObj.lastArticle.id && history.push('/article/detail/' + articleObj.lastArticle.id)}>上一篇：{articleObj.lastArticle.title || '没有上一篇了'}</p>
                                <p onClick={() => articleObj.nextArticle.id && history.push('/article/detail/' + articleObj.nextArticle.id)}>下一篇：{articleObj.nextArticle.title || '没有下一篇了'}</p>
                            </div>
                        </div>
                    </div>
                </MyCard>
            </div>
            
            <div className="anchor">
                <MyCard title="目录">
                    <div className="anchor-content">
                        <Anchor targetOffset={70} showInkInFixed={true} getContainer={() => document.getElementById('article-top-c')}>
                            {
                                articleObj.contents.map((item, index) => {
                                    return (
                                        Array.isArray(item) ? 
                                        <Link href={'#' + item[0].link} key={index} title={item[0].title}>
                                            {
                                                item.map((item, i) => {
                                                    return (
                                                        i === 0 ? '' :
                                                        <Link href={'#' + item.link} key={index + '-' + i} title={item.title} />
                                                    )
                                                })
                                            }
                                        </Link> :
                                        <Link href={'#' + item.link} key={index} title={item.title} />
                                    )
                                })
                            }
                        </Anchor>
                    </div>
                </MyCard>
            </div>

            {/* 点赞收藏 */}
            <LikeContainer onClick={() => likeArticle(articleObj.id)}>
                <Badge count={articleObj.likecount || 0} className="like-badge" style={{backgroundColor: articleObj.isLike ? '#eb2f96' : '#999'}}></Badge>
                <LikeFilled style={{fontSize: 18, color: articleObj.isLike ? '#eb2f96' : '#999'}}/>
            </LikeContainer>
            <CollectContainer onClick={() => collectArticle(articleObj.id, articleObj.title, articleObj.desc)}>
                <StarFilled style={{fontSize: 18, color: articleObj.isCollect ? '#ffd139' : '#999'}}/>
            </CollectContainer>
        </Container>
    )
}

const mapState = (state) => ({
    
})

const mapDispatch = (dispatch) => ({
    changeDetailTopDis(data){
        dispatch(changeDetailTopDis(data))
    },
    changeDetailObj(data){
        dispatch(changeDetailObj(data))
    }
})

export default connect(mapState, mapDispatch)(Detail)